import React, { Component } from 'react';
import PropTypes from "prop-types";
import {StyleSheet,Text,View,TouchableOpacity,Image ,Platform} from 'react-native';
import ListView from 'deprecated-react-native-listview'
import SwipeListView from './SwipeListView.js';
import SwipeRow from './SwipeRow.js';


import Label from '../label/index.js';
import Color from "../../config/theme/standard/color.js";
import fontSize from '../../config/theme/standard/fonts.js';


const  ds = new ListView.DataSource({rowHasChanged:(r1,r2) => r1 !== r2});

export default class SwipeAction extends Component{
    constructor(props) {
        super(props);
        this.state={
            prevPropsData: ds.cloneWithRows(props.dataSource),
            data:ds.cloneWithRows(props.dataSource),
            //rows:props.dataSource,
        };
        this.selected = false;
        this.text = null;
        this.deleteItem=this.deleteItem.bind(this);
        this._renderRow=this._renderRow.bind(this);
        this.otherEvent=this.otherEvent.bind(this);
        this.itemClickEvent=this.itemClickEvent.bind(this);
    }
    deleteItem(rowData,sectionID,rowID,rowMap){
        if(this.props.isDeleteType){
            let newData = [];
            let dataSource=this.props.dataSource;
            for(var i=0;i<dataSource.length;i++){
                if(dataSource[i]!=rowData){
                    newData.push(dataSource[i])
                };
    
            };
            dataSource.splice(rowID,1);
    
            this.setState({
                data:ds.cloneWithRows(newData)
            });
    
            if(typeof(this.props.deleteEvent) === 'function'){
                this.props.deleteEvent(rowData,sectionID,rowID,rowMap);
            };
            rowMap[`${sectionID}${rowID}`].closeRow();
        }else{
            if(typeof(this.props.deleteEvent) === 'function'){
                this.props.deleteEvent(rowData,sectionID,rowID,rowMap);
            };
    
        }
     
    }
    otherEvent(rowData,sectionID,rowID,rowMap){
        if(typeof(this.props.otherEvent) === 'function'){
            this.props.otherEvent(rowData,sectionID,rowID,rowMap);
        };
    }
    itemClickEvent(event,rowData,sectionID,rowID,rowMap){
        if(Platform.OS=='web'){
            event.preventDefault()
        };
        if(typeof(this.props.onPress) === 'function'){
            this.props.onPress(rowData,sectionID,rowID,rowMap);
        };
    }
 
    static getDerivedStateFromProps(nextProps, prevState) {
        let dataTmp;
        if(nextProps.dataSource){
            dataTmp = ds.cloneWithRows(nextProps.dataSource)
        }
        
        if ( dataTmp && (dataTmp !== prevState.prevPropsData)) {
            return {
                prevPropsData: dataTmp,
                data: dataTmp,
            };
        }
        return null;
    }

    _renderRow(rowData,sectionID,rowID,rowMap){
        const props = rowData;

        let letImgIcon=null;//左侧图片
        let titleComponent=null;
        let subTitleComponent=null;
        let statusComponent=null;
        let statusTextComponent=null;
        let descriptionComponent=null;
        let descriptionTextComponent=null;
        let imgArrowItem=null;
        let deleteComponent=<View/>;
        let hiddenFirstComponent=<View/>;
        let moveX=-70;
        let containerStyle = [styles.container]
        //是否有左侧图片
        if(props.hasLeftImg){
            letImgIcon = <View style={{marginRight:12}}>
                            <Image
                                source = {props.leftImg}
                                style = {styles.leftImage}
                                resizeMode={"contain"}
                            />
                         </View>;
        }
        
        //是否有左侧title
        if(props.title){
            let title =  props.title 
            let titleStyles = [styles.title];
            if(props.titleStyle){
                titleStyles.push(props.titleStyle);
            }
            titleComponent=<Label  labelStyle={titleStyles} text={title} numberOfLines={1} />
        };
        //是否有左侧subtitle
        if(props.subTitle){

            let subTitle = props.subTitle 
            let subTitleStyles = [styles.subTitle];
            if(props.subTitleStyle){
                subTitleStyles.push(props.subTitleStyle);
            }
            subTitleComponent=<Label labelStyle={subTitleStyles} text={subTitle} numberOfLines={1}/>
            containerStyle.push({minHeight: 67, alignItems: 'flex-start', paddingTop: 12})
        };
        if(props.subTitleChild) {
            containerStyle.push({minHeight: 67, alignItems: 'flex-start', paddingTop: 12})
        }

        //是否有右侧statusText（传入文字）
        if(props.statusText) {
            let statusText = props.statusText;
            let statusTextStyle = [styles.statusText];
            if(props.statusTextStyle){
                statusTextStyle.push(props.statusTextStyle);
            }
            statusTextComponent = <Label labelStyle={statusTextStyle} text={statusText} numberOfLines={1}/>
        };
        //是否有右侧status（传入组件）
        if(props.status){
           statusComponent=props.status;
        };

         //是否有右侧descriptionText（传入文字）
         if(props.descriptionText) {
            let descriptionText = props.descriptionText;
            let descriptionTextStyle = [styles.descriptionText];
            if(props.descriptionTextStyle){
                descriptionTextStyle.push(props.descriptionTextStyle);
            }
            descriptionTextComponent = <Label labelStyle={descriptionTextStyle} text={descriptionText} numberOfLines={1}/>
        };

        //是否有右侧description （传入组件）
        if(props.description){
            descriptionComponent=props.description;
        };

        if(props.subTitle && props.description){
            let subTitle = props.subTitle.length > 10 ? props.subTitle.slice(0, 9) + '...' : props.subTitle 
            let subTitleStyles = [styles.subTitle];
            if(props.subTitleStyle){
                subTitleStyles.push(props.subTitleStyle);
            }
            subTitleComponent=<Label labelStyle={subTitleStyles} text={subTitle}/>
            descriptionComponent=props.description;
        };
        //是否有右侧箭头
        if(props.hasArrow){
            imgArrowItem = <View style={styles.imageContainer}>
	    <Image
                source = {require('../../assets/list_arrow_right.png')}
                style = {styles.image}
		/>
		</View>;
	    }else {            
	    	containerStyle.push({paddingRight: 15})
        };
        //是否有隐藏按钮
        if(props.hasHiddenBtn){
            //是否有删除按钮
            if(props.deleteText){
                deleteComponent=<TouchableOpacity activeOpacity={1}  onPress={()=>{this.deleteItem(rowData,sectionID,rowID,rowMap)}}>
                    <View style={[styles.right,{backgroundColor:props.deleteBgColor?props.deleteBgColor:Color.list.deleteBackground}]}>
                        <Label labelStyle={styles.rightStyle} text={props.deleteText}/>
                    </View>
                </TouchableOpacity>
            };
            //是否其他隐藏按钮
            if(props.otherHiddenBtnText){
                hiddenFirstComponent=<TouchableOpacity activeOpacity={1} onPress={()=>{this.otherEvent(rowData,sectionID,rowID,rowMap)}}>
                    <View style={[styles.right,{backgroundColor:props.otherHiddenBtnBg?props.otherHiddenBtnBg:Color.list.otherBackground}]}>
                        <Label labelStyle={styles.rightOtherStyle} text={props.otherHiddenBtnText}/>
                    </View>
                </TouchableOpacity>
            };
            //判断移动的距离
            if(props.deleteText &&  props.otherHiddenBtnText){
                moveX=-140;
            };

        };

        let _this=this;
        let disabled=false;
        if(props.disabled==0 || props.disabled=="0"){
            disabled=true;
        };
        return (
            <SwipeRow
                rightOpenValue={moveX}
                disableLeftSwipe={!props.hasHiddenBtn}
                disableRightSwipe={true}
                swipeToOpenPercent={50}
                ref={(swipeRow) => {
                        this[props.ref] = swipeRow;
                        if (swipeRow) {
                            swipeRow.closeRow();
                        }
                    }}
            >
                <View style={styles.rowBack}>
                    <View/>
                    <View style={{flexDirection:'row',height:'100%'}}>
                        {hiddenFirstComponent}
                        {deleteComponent}
                    </View>
                </View>
            <TouchableOpacity disabled={disabled} activeOpacity={1} onPress={(event)=>{this.itemClickEvent(event,rowData,sectionID,rowID,rowMap)}}>
                <View style={[containerStyle,props.containerStyle]}>
                    {letImgIcon}
                    {props.leftComponent?props.leftComponent:null}
                    <View style={styles.leftContainer}>
                        {titleComponent}
                        {props.titleChild?props.titleChild:null}
                        {subTitleComponent}
                        {props.subTitleChild?props.subTitleChild:null}
                    </View>
                    <View style={styles.rightContainer}>
                        {statusComponent}
                        {statusTextComponent}
                        {descriptionComponent}
                        {descriptionTextComponent}
                    </View>
                    {imgArrowItem}
                </View>
            </TouchableOpacity>
            </SwipeRow>
        );
    }

    render() {
        return (
            <SwipeListView
                dataSource={this.state.data}
                recalculateHiddenLayout={false}
                enableEmptySections={true}
                renderRow={(data,sectionID,rowID,rowMap)=>this._renderRow(data,sectionID,rowID,rowMap)}
            />
        )
    }
}


SwipeAction.propTypes={
    dataSource:PropTypes.array,
    deleteEvent:PropTypes.func,
    otherEvent:PropTypes.func,
    onPress: PropTypes.func,
    containerStyle:PropTypes.any , 
    isDeleteType:PropTypes.bool,
}

SwipeAction.defaultProps = {
    dataSource:[],
    containerStyle:{},
    isDeleteType:true
};



const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        backgroundColor: '#fff',
        borderColor: Color.border,
        borderBottomWidth: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingLeft:15,
        paddingRight:8,
        minHeight:44
    },
    leftImage:{
        width:28,
        height:28,
        resizeMode: 'contain',
    },
    leftContainer:{
        flex:1,
        flexDirection: 'column',
        justifyContent: 'center'
    },
    title:{
        fontSize:fontSize.list.titleFontSize,
        color:Color.list.title,
        fontWeight:'400'
    },
    subTitle:{
        fontSize:fontSize.list.subTitleFontSize,
        color:Color.list.subTitle,
        fontWeight:'400',
        marginTop: 5,
    },
    statusText:{
        fontSize:fontSize.list.statusFontSize,
        color:Color.list.status,
        fontWeight:'400',
        marginLeft: 25
    },
    descriptionText:{
        fontSize:fontSize.list.descriptionFontSize,
        color:Color.list.description,
        fontWeight:'400',
        marginTop: 5
    },
    rightContainer: {
        flexDirection: 'column',
        alignItems: 'flex-end',
        justifyContent: 'center',

    },
    imageContainer:{
        marginLeft:4,
        alignItems: 'flex-end',
        width: 28
    },
    image:{
        width: 28,
        height: 28
    },
    rowBack: {
        alignItems: 'center',
        flexDirection: 'row',
        justifyContent: 'space-between',
        flex: 1
    },
    right: {
        flexDirection:"row",
        width: 70,
        height:100+'%',
        alignItems: 'center',
        justifyContent: 'center'
    },
    rightStyle:{
        color:Color.list.HiddenBtn,
        fontSize:fontSize.list.HiddenBtnFontSize,
        fontWeight:'400'
    },
    rightOtherStyle:{
        color:Color.list.otherHiddenBtn,
        fontSize:fontSize.list.HiddenBtnFontSize,
        fontWeight:'400'
    }
})
